<?php
/**
 * Created by PhpStorm.
 * User: 李闯
 * Date: 2020/7/7
 * Time: 13:07
 * Content: 团队
 */

namespace app\admin\controller;

use app\reuse\controller\ResponseJson;
use app\service\MemberService;
use app\service\ResourceService;
use think\Db;
use think\facade\Session;

class Team extends Common
{
    use ResponseJson;

    function __construct()
    {
        parent::__construct();
        // 登录校验
        $this->IsLogin();
    }

    /*
     * @param null
     * @content 团队列表
     * @return array
     * */
    function index()
    {
        if (input("get.active") == "ajax") {

            # 定义listRows
            $listRows = input('post.limit');
            if (empty($listRows)) {
                $listRows = 10;
            }
            # 定义where
            $_where = '';
            $order = 'create_time desc';
            # 排序筛选
            $mark = input('post.mark');
            if (!empty($mark)) {
                if ($mark == 'peopleRanking') {
                    $order = 'team_num desc';
                }
                if ($mark == 'revenueRanking') {
                    $order = 'team_earnings desc';
                }
            }
            # 搜索条件
            $searchParams = json_decode(input('post.searchParams'), true);
            if (!empty($searchParams)) {
                if (is_numeric($searchParams['search'])) {
                    #搜索手机号
                    $_where .= " and m.phone like '%" . $searchParams['search'] . "%'";

                } else {
                    # 姓名搜索
                    if (!empty($searchParams['search'])) {
                        $_where .= " and t.title like '%" . $searchParams['search'] . "%'";
                    }
                }
            }
            $info = Db::table('team t')
                ->field("t.*,m.name,(select count(id) from member mm where mm.team_id=t.id and mm.status=5 and mm.fictitious != 1) team_num")
                ->join("member m", 'm.code = member_code')
                ->where("is_fake = 1" . $_where)
                ->order($order)
                ->paginate($listRows, false, ['query' => request()->param()]);
            # 返回数据
            return $this->jsonSuccessData($info);
        } else {
            $this->assign('mark', input('get.mark'));
            return $this->fetch();

        }

    }

    /*
    * @param null
    * @content 查询领头人信息
    * @return array
    * */
    function getMember()
    {
        $memberCode = input("get.memberCode");
        if (!empty($memberCode)) {
            $mark = input("get.mark");
            if (!empty($mark)) {
                #查询的是玩家信息
                $info = Db::table('member m')
                    ->field('m.*,ml.title levelTitle,t.title teamTitle,mc.wx_number,ali_number,unionpay_number,mp.income,
                mp.ruby,mp.materials,mp.integral,mp.gold,t.team_num')
                    ->join('member_level ml', 'ml.level=m.level', 'left')
                    ->join('team t', 't.id=m.team_id and t.is_fake=1', 'left')
                    ->join('member_collection mc', 'mc.member_code=m.code', 'left')
                    ->join('member_property mp', 'mp.member_code=m.code and mp.is_fake=1', 'left')
                    ->where(array('m.code' => $memberCode))
                    ->find();
            } else {
                #查询领导人信息
                $info = Db::table('team t')
                    ->field("m.*,ml.title levelTitle,t.title teamTitle,mc.wx_number,ali_number,unionpay_number,mp.income,
                mp.ruby,mp.materials,mp.integral,mp.gold,t.team_num")
                    ->join('member m', 'm.code= t.member_code')
                    ->join('member_level ml', 'ml.level=m.level', 'left')
                    ->join('member_collection mc', 'mc.member_code=t.member_code', 'left')
                    ->join('member_property mp', 'mp.member_code=m.code and mp.is_fake=1', 'left')
                    ->where("t.member_code = '$memberCode'")
                    ->find();
            }
            $this->assign('info', $info);
            $this->assign('memberCode', $memberCode);
            return $this->fetch("member_detail");
        } else {
            #搜索的手机号
            $phone = input("get.phone");
            #团队id
            $teamId = input("get.teamId");
            #type 类型为 teamCreate 时  是创建团队搜索手机号时的玩家信息
            $type = input("get.type");
            #团队名称
            $teamTitle = input("get.teamTitle");
            #原来的 玩家id
            $oldmemberCode = input("get.oldmemberCode");
            if (!empty($phone)) {
                if (input("get.active") == "ajax") {
                    $member = Db::table('member m')
                        ->field('m.*,ml.title levelTitle,t.title teamTitle,mc.wx_number,ali_number,unionpay_number,mp.income,
                mp.ruby,mp.materials,mp.integral,mp.gold,t.team_num')
                        ->join('member_level ml', 'ml.level=m.level', 'left')
                        ->join('team t', 't.id=m.team_id', 'left')
                        ->join('member_collection mc', 'mc.member_code=m.code', 'left')
                        ->join('member_property mp', 'mp.member_code=m.code', 'left')
                        ->where("(m.type = 1 or m.type = 2)  and m.phone='$phone'")
                        ->order(array('type' => 'asc'))
                        ->paginate(10, false, ['query' => request()->param()]);
                    return $this->jsonSuccessData($member);
                } else {
                    $this->assign('phone', $phone);
                    $this->assign('teamId', $teamId);
                    $this->assign('type', $type);
                    $this->assign('teamTitle', $teamTitle);
                    $this->assign('oldmemberCode', $oldmemberCode);

                    return $this->fetch("member_replace");
                }
            }
        }
    }

    /*
     * @param null
     * @content 团队修改
     * @return array
     * */
    function write()
    {
        if (input("get.active") == "ajax") {
            $info = input("post.");
            $id = input("post.id");
            #查询团队名称是否重复
            $teamtitle = Db::table("team")->where("id != $id and title = '" . $info['title'] . "'")->find();
            if (empty($teamtitle)) {
                if (!empty($info)) {
                    if ($info['matching_type'] == 1) {
                        #独立
                        $info['team_set'] = '0';
                    } else {
                        #综合
                        $info['team_set'] = implode(",", $info['team_set']);

                    }
                    #执行添操作
                    $result = Db::table("team")->where("id = $id")->update($info);
                    # 返回数据
                    return array("status" => true, 'msg' => '提交成功');
                } else {
                    return array("status" => false, 'msg' => '没有接收到参数');
                }
            } else {
                return array("status" => false, 'msg' => '团队名称重复,请换一个!');
            }

        } else {
            /*         $search = input("post.search");
                     $_where ='';
                         #搜索数据 证明搜索 得到的  把搜索的值都存到sessio 数组 最后数组遍历获取
                         $_where .= " and t.title like '%" . $search . "%'";

                         #查询member 数据查出来
                         $memberSearch = Db::table('member')->where($_where)->field('id,code,name')->select();
                         if(!empty($memberSearch)){
                             #是否有缓存
                             $searchMember = Session::get("searchMember");
                             $searchMemberId = array();
                             if(empty($searchMember)){
                                 #把查出来的值 存到session
                                 Session::set('searchMember',$memberSearch);
                             }else{
                                 foreach($searchMember as $s =>$sv){
                                     array_push($searchMemberId,$sv['id']);
                                 }
                                 #把新的值 放在原来数组后面 插入数组
                                 foreach ($memberSearch as $k=>$v){
                                     #判断新搜索的数据 id  是否和 缓存里的相同
                                     if(!in_array($v['id'],$searchMemberId)){
                                         array_push($searchMember,$v);
                                     }
                                 }
                                 Session::set('searchMember',$searchMember);
                             }
                             $sessionMember = Session::get("searchMember");
                             $member = $sessionMember;
                         }*/

            #团队id
            $id = input("get.id");
            #查询类型 #查出这个团队的团队id 集合
            $team = Db::table("team t")
                ->field("t.*,m.name memberName")
                ->join('member m', 'm.code = t.member_code')->where("t.id= $id")->find();
            #查询这个表中除了自己的所有团队 的名称
            $memberTeam = Db::table("team")->where("id!= $id")->select();
            #目的   综合匹配时  把查出来的和所有的类型 匹配一下  有则默认
            $teamSet = explode(",", $team['team_set']);
            $this->assign("team", $team);
            $this->assign("memberTeam", $memberTeam);
            $this->assign("teamSet", $teamSet);
            $this->assign("id", $id);

            return $this->fetch();
        }

    }

    /*
   * @param phone 用户手机号
   * @content 更换用户
   * @return array
   * */
    function memberTeamReplace()
    {
        #旧的玩家ID
        $oldmemberCode = input("post.oldmemberCode");
        $memberCode = input("post.memberCode");
        $teamId = input("get.teamId");
        if (!empty($memberCode)) {
            $team = Db::table("team")->where("id = '$teamId'")->update(array("member_code" => $memberCode));
            if (!empty($oldmemberCode)) {
                #看原来的领导人 是否还是领导人  不是 则状态修改为正常
                $oldMember = Db::table("team")->field('member_code')->where("member_code = $oldmemberCode")->find();
                if (empty($oldMember)) {
                    #修改状态
                    Db::table("member")->where("code = $oldmemberCode")->update(array('type' => 1));
                }
            }
            return array("status" => true, 'msg' => '更换成功');

        }
    }

    /*
    * @param null
    * @content 查询团队对应 玩家信息
    * @return array
    * */
    function getTeamMember()
    {
        $teamId = input("get.teamId");
        if (!empty($teamId)) {
            if (input("get.active") == "ajax") {
                $_where = "m.team_id = '$teamId'";
                # 定义listRows
                $listRows = input('post.limit');
                if (empty($listRows)) {
                    $listRows = 15;
                }
                # 搜索条件
                $searchParams = json_decode(input('post.searchParams'), true);
                if (!empty($searchParams)) {
                    if (is_numeric($searchParams['search'])) {
                        #搜索手机号 和玩家ID
                        $_where .= " and m.phone like '%" . $searchParams['search'] . "%' ";

                    } else {
                        # 姓名搜索
                        if (!empty($searchParams['search'])) {
                            $_where .= " and (m.name like '%" . $searchParams['search'] . "%' or m.code like '%" . $searchParams['search'] . "%')";
                        }
                    }
                    # 时间筛选
                    if (!empty($searchParams['register_min'])) {
                        $_where .= " and date(m.register_time) >= '" . $searchParams['register_min'] . "'";
                    }
                    if (!empty($searchParams['register_max'])) {
                        $_where .= " and date(m.register_time) <= '" . $searchParams['register_max'] . "'";
                    }
                }
                #查询用户信息
                # 查询列表
                $info = Db::table('member m')
                    ->field('m.*,ml.title levelTitle,t.title teamTitle,mc.wx_number,ali_number,unionpay_number,mp.income,
                mp.ruby,mp.materials,mp.integral,mp.gold,t.team_num')
                    ->join('member_level ml', 'ml.level=m.level', 'left')
                    ->join('team t', 't.id=m.team_id', 'left')
                    ->join('member_collection mc', 'mc.member_code=m.code', 'left')
                    ->join('member_property mp', 'mp.member_code=m.code', 'left')
                    ->where($_where)
                    ->order(array('id' => 'desc'))
                    ->paginate($listRows, false, ['query' => request()->param()]);
                # 返回数据
                return $this->jsonSuccessData($info);

            } else {
                #查询领导人信息
                $info = Db::table('team t')
                    ->field("m.*,ml.title levelTitle,t.title teamTitle,mc.wx_number,ali_number,unionpay_number,mp.income,
                mp.ruby,mp.materials,mp.integral,mp.gold,t.team_num")
                    ->join('member m', 'm.code= t.member_code')
                    ->join('member_level ml', 'ml.level=m.level', 'left')
                    ->join('member_collection mc', 'mc.member_code=t.member_code', 'left')
                    ->join('member_property mp', 'mp.member_code=m.code and mp.is_fake=1', 'left')
                    ->where("t.id = $teamId")
                    ->find();
                $this->assign('info', $info);
                $this->assign('code', $info['code']);
                $this->assign('teamId', $teamId);
                return $this->fetch("member_team");
            }
        }
    }

    /*
     * @param null
     * @content 创建团队页面
     * @return array
     * */
    function create()
    {
        if (input("get.active") == "teamCreate") {
            $info = input("get.");
            #点击去创建进的页面
            if (input("get.action") == "ajax") {

                $post = input("post.");
                #查询团队名称是否重复
                $teamtitle = Db::table("team")->where(array("title" => $post['title']))->find();
                if (empty($teamtitle)) {
                    if ($post['matching_type'] == 1) {
                        #独立
                        $post['team_set'] = '0';
                    } else {
                        #综合
                        $post['team_set'] = implode(",", $post['team_set']);

                    }

                    $post['create_time'] = date("Y-m-d H:i:s");
                    # 查询上一个团队的标识 , 该团队标识为上一个团队标识加一
                    $lastTeam_code = Db::table('team')->field('team_code')
                        ->where(array('is_fake' => 1))
                        ->order('id desc')->find()['team_code'];
                    if (!empty($lastTeam_code)) {
                        $before = substr($lastTeam_code, 0, 1);
                        $after = substr($lastTeam_code, 1);
                        $before++;
                        if ($before == 'AA') {
                            $before = 'A';
                            $after = intval($after) + 1;
                        }
                        $team_code = trim($before . $after);
                    } else {
                        # 为空 , 第一个添加
                        $team_code = 'A';
                    }
                    $post['team_code'] = $team_code;

                    $teamId = Db::table("team")->insertGetId($post);
                    if ($teamId) {
                        # 查询这个人的上一个团队
                        $child=getsTeamChild($info['memberCode']);
                        if(empty($child)){
                            $child=array();
                        }
                        //array_push($child,$info['memberCode']);
                        if(!empty($child)){
                            # 更改所有人团队
                            $code_collon=implode(',',array_map('change_to_quotes', $child));
                            Db::table("member")->where("code in (".$code_collon.")")->update(array("team_id"=>$teamId));
                            foreach($child as $chk=>$chv){
                                MemberService::changeRedis($chv);
                            }
                        }
                        $old_teamId = Db::table('member')->field('team_id')->where(array('code' => $info['memberCode']))->find()['team_id'];
                        if ($teamId != $old_teamId and !empty($old_teamId)) {
                            # 说明修改了团队 , 要修改团队人数
                            # 原团队人数减一
                            Db::table('team')->where(array('id' => $old_teamId))->setDec('team_num',count($child));
                        }
                        # 新团队人数增加
                        Db::table('team')->where(array('id' => $teamId))->setInc('team_num',count($child));
                        #这个领导人改为合伙人状态 , 清空上级 , 团队id为当前创建的团队id
                        Db::table("member")->where("code = '" . $info['memberCode'] . "'")->update(array("type" => 2, 'p_code' => '', 'team_id' => $teamId));
                        # 更新redis
                        MemberService::changeRedis($info['memberCode']);
                        return array("status" => true, 'msg' => '操作成功');
                    } else {
                        return array("status" => false, 'msg' => '提交失败');
                    }
                } else {
                    return array("status" => false, 'msg' => '团队名称重复');

                }

            } else {
                $search = input("post.search");
                $_where = '';
                if (!empty($search)) {
                    #搜索数据 证明搜索 得到的  把搜索的值都存到sessio 数组 最后数组遍历获取
                    $_where .= " and t.title like '%" . $search . "%'";
                }


                #查询member 数据查出来
                #查询所有团队
                $memberTeam = Db::table("team")->field('id,title')->where($_where)->select();
                if (!empty($memberTeam)) {
                    #是否有缓存
                    $searchMember = Session::get("searchMember");
                    $searchMemberId = array();
                    if (empty($searchMember)) {
                        #把查出来的值 存到session
                        Session::set('searchMember', $memberTeam);
                    } else {
                        foreach ($searchMember as $s => $sv) {
                            array_push($searchMemberId, $sv['id']);
                        }
                        #把新的值 放在原来数组后面 插入数组
                        foreach ($memberTeam as $k => $v) {
                            #判断新搜索的数据 id  是否和 缓存里的相同
                            if (!in_array($v['id'], $searchMemberId)) {
                                array_push($searchMember, $v);
                            }
                        }
                        Session::set('searchMember', $searchMember);
                    }
                    $sessionMember = Session::get("searchMember");
                    $member = $sessionMember;
                }
                $memberTeam = Db::table("team")->field('id,title')->where($_where)->select();

                $this->assign("memberTeam", $memberTeam);
                $this->assign('teamTitle', $info['teamTitle']);
                $this->assign('memberName', $info['memberName']);
                $this->assign('memberCode', $info['memberCode']);
                return $this->fetch("team_create");
            }
        } else {
            #列表点击添加进入的页面
            return $this->fetch();

        }
    }

    /*
    * @param null
    * @content 创建团队页面
    * @return array
    * */
    function member_so()
    {
        $phone = input("post.phone");
        if (!empty($phone)) {
            $mmeber = Db::table("member")->field('id')->where("phone = '$phone'and(type = 1 or type = 2)")->find();
            if (!empty($mmeber)) {
                return array('status' => true);
            } else {
                return array('status' => false, 'msg' => '玩家数据为空,请换个手机号!');
            }
        } else {
            return array('status' => false, 'msg' => '请输入正确的手机号!');
        }

    }
}